package com.lqfan.autoAnswerQ.service.quesBank.impl;

import com.lqfan.autoAnswerQ.controller.importQuestions.PoiWordController;
import com.lqfan.autoAnswerQ.model.fileType.FileType;
import com.lqfan.autoAnswerQ.model.quesBank.Question;
import com.lqfan.autoAnswerQ.dao.quesBank.QuestionMapper;
import com.lqfan.autoAnswerQ.service.fileType.IFileTypeService;
import com.lqfan.autoAnswerQ.service.quesBank.IQuestionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lqfan.autoAnswerQ.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lqfan
 * @since 2020-04-05
 */
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements IQuestionService {
    private static final Logger logger = LoggerFactory.getLogger(PoiWordController.class);
    private static final String filePath = System.getProperty("user.dir");

    @Autowired
    private IFileTypeService fileTypeService;

    @Override
    @Transactional(isolation= Isolation.DEFAULT,propagation= Propagation.REQUIRED,rollbackFor = Exception.class)
    public boolean saveQuesBank(MultipartFile questionFile, MultipartFile answerFile, String path, String src, String fileName, int fileType, String userId) {

        //获取文件名
        String qName = questionFile.getOriginalFilename();
        //获取文件后缀名
        logger.info(qName.substring(qName.lastIndexOf(".")));
        String suffixName = qName.substring(qName.lastIndexOf(".")+1);
        //属于什么文件（word 、ppt、pdf）
        Integer questionFileType;
            if (suffixName.equals("pdf")){
                questionFileType = 4;
            }else if (suffixName.equals("xlsx")||suffixName.equals("xls")){
                questionFileType = 3;
            }else if (suffixName.equals("doc")||suffixName.equals("docx")){
                questionFileType = 1;
            }else if (suffixName.equals("ppt")){
                questionFileType = 2;
            }else {
                questionFileType = 5;
            }
        //重新生成文件名
        qName = UUID.randomUUID()+suffixName;
        //保存文件
//        int saveResult = saveFile(questionFile,userId, qName, fileType, path);
        //1.保存文件
        int saveResult = saveFile(questionFile,userId, fileName, fileType, src);
        if (saveResult == 0){
            return false;
        }

        //2.保存题库
        Question quesBank = new Question();
        quesBank.setFilePath(src);
        quesBank.setQuestionName(fileName);
        quesBank.setQuestionFileType(questionFileType);
        quesBank.setUserId(userId);
        boolean saveRes = super.save(quesBank);

        //解析题库文件

        return saveRes;
    }

    /**
     * 保存文件
     * type 为文件类型（经典练习、模拟练习）
     */
    public int saveFile(MultipartFile file, String userId, String fileName, int type, String path){
        //存放路径
//        String src = filePath + "/source/"+type+"/" + userId+path;
        try {
            //保存文件
            FileUtil.uploadFile(file.getBytes(), path, fileName);
            String   save= fileTypeService.selectFilePid(path);
            if (save==null){
                boolean res = fileTypeService.saveFileType(path, type, userId);
                if (!res){
                    logger.error("保存文件路径失败");
                    return 0;
                }
            }else {
                logger.error("保存文件路径存在");
            }


            logger.info("保存题库文件成功");
            return 1;
        } catch (Exception e) {
            logger.error("保存题库文件失败");
            e.printStackTrace();
            return 0;
        }
    }

    public boolean updateDoNum(String userId,String id){
        boolean updateDoNum = baseMapper.updateDoNum(userId,id);
        return updateDoNum;
    }
}
